local meta = FindMetaTable( "Player" )

if ( not meta ) then
	return
end

function meta:GetPlayerDataFile()
	return ( "funfair/player_" .. self:UniqueID() .. ".txt" )
end

function meta:SavePlayerData()
	local PlayerData = {}
	
	PlayerData["tokens"] = self:GetNWInt( "tokens", 0 )
	PlayerData["ticket"] = self.Ticket
	
	file.Write( self:GetPlayerDataFile(), util.TableToKeyValues( PlayerData ) )	
	print( "Saved Data File:", self:Nick().. "\n" )	
	return true
end

function meta:LoadPlayerData()
	if not file.Exists( self:GetPlayerDataFile() ) then
		print( "No Data File:", self:Nick() )
		self:ChatPrint("Welcome to FunFair, this appears to be your first time playing, you have been given 100 Tokens.")
		self:AddTokens(100)
		return false
	else
		PlayerData = util.KeyValuesToTable( file.Read( self:GetPlayerDataFile() ) )	
		self:SetNWInt( "tokens", PlayerData["tokens"] )
		self.Ticket = PlayerData["ticket"]	
		print( "Loaded Data File:", self:Nick().. "\n" )
		return true	
	end	
end

function meta:GetTokens()
	return self:GetNWInt( "tokens", 0 )
end

function meta:AddTokens( amount )
	if ( amount < 0 ) then
		return false
	end
	self:SetNWInt( "tokens", self:GetNWInt("tokens") + amount )
	self:SavePlayerData()
	print( "Added Tokens", self:Nick(), amount .. "\n" )
	return true
end

function meta:SubTokens( amount )
	if ( amount < 0 ) then
		return false
	end
	local newTokens = self:GetNWInt( "tokens" ) - amount
	if ( newTokens < 0 ) then
		return false
	end
	self:SetNWInt( "tokens", newTokens )
	self:SavePlayerData()
	print( "Subtracted Tokens", self:Nick(), amount.. "\n" )
	return true
end